package com.example.demo.utils;


import com.example.demo.bean.CheckCode;
import com.example.demo.service.OssService;
import com.example.demo.service.impl.OssServiceImpl;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JWLoginUtil {
    private String xh;
    private String mm;
    private String name;
    public String responseCookie = "";
    private static final int STATE_LOGIN_JW_SUCCESS = 1;
    private static final int STATE_LOGIN_JW_CHECKCODE_ERROR = -1;
    private static final int STATE_LOGIN_JW_REPAIRED = -2;
    private static final int STATE_LOGIN_JW_USER_NOT_EXIST = -3;
    private static final int STATE_LOGIN_JW_PASSWORD_ERROR = -4;
    private static final int STATE_LOGIN_JW_FAILED = -5;
    private static String VIEWSTATE = "";
    private static HttpURLConnection con;
    private int responseCode = 404;
    private static final String login_url = "http://jwjx.njit.edu.cn/default2.aspx";
    private static final String checkcode_url = "http://jwjx.njit.edu.cn/CheckCode.aspx";
    private String main_url;
    private String url_encoder = "GB2312";
    private String viewState = "";


    private String currentPage = "";

    private String doPost(String url, Map<String, String> header, Map<String, String> params) {
        try {

            //请求参数
            URL strURL = new URL(url);
            con = (HttpURLConnection) strURL.openConnection();
            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);

            if (header != null) {
                for (Iterator<String> iterator = header.keySet().iterator(); iterator.hasNext(); ) {
                    String name = iterator.next();
                    String value = String.valueOf(header.get(name));
                    con.setRequestProperty(name, value);
                }
            }


            //构建post表单
            StringBuilder formParams = new StringBuilder();
            if (params != null) {
                for (Iterator<String> iterator = params.keySet().iterator(); iterator
                        .hasNext(); ) {
                    String name = iterator.next();
                    String value = String.valueOf(params.get(name));
                    formParams.append(URLEncoder.encode(name, url_encoder) + "=" + URLEncoder.encode(value, url_encoder));
                    if (iterator.hasNext())
                        formParams.append("&");
                }
            }
            con.setRequestProperty("Content-Length", String.valueOf(formParams.toString().length()));
            //设置是否让系统自动处理重定向
            con.setInstanceFollowRedirects(false);

            //写入参数
            OutputStream out = con.getOutputStream();
            out.write(formParams.toString().getBytes(url_encoder));
            out.flush();
            out.close();
            //返回数据
            StringBuffer sb = new StringBuffer("");
            responseCode = con.getResponseCode();
            if (responseCode == 200 || responseCode == 302) {
                InputStream is = con.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, url_encoder);
                BufferedReader bf = new BufferedReader(isr);
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = bf.readLine()) != null) {
                    sb.append(line + NL);
                }
                bf.close();
                return new String(sb);
            } else {
                con.disconnect();
                return "状态码" + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            con.disconnect();
        }
        return "error";
    }

    private String doGet(String url, Map<String, String> header) {
        StringBuffer sb = new StringBuffer();
        try {
            URL strURL = new URL(url);
            con = (HttpURLConnection) strURL.openConnection();
            if (header != null) {
                for (Iterator<String> iterator = header.keySet().iterator(); iterator
                        .hasNext(); ) {
                    String name = iterator.next();
                    String value = header.get(name);
                    con.setRequestProperty(name, value);
                }
            }
            con.connect();
            if (con.getResponseCode() == 200) {
                InputStream is = con.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, url_encoder);
                BufferedReader br = new BufferedReader(isr);
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                return new String(sb);
            } else
                return "failed";

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            con.disconnect();
        }
        return "error";
    }


    public String getViewState(String str) {
        if (str.contains("__VIEWSTATE")) {
            int init = str.indexOf("__VIEWSTATE");
            int start = str.indexOf("value=", init) + 7;
            int end = str.indexOf("\"", start);
            return str.substring(start, end);
        }
        return null;
    }


    public static CheckCode getCheckCode(String key) throws Exception {
        OssService ossService = new OssServiceImpl();
        URL strURL = new URL(checkcode_url);
        con = (HttpURLConnection) strURL.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setInstanceFollowRedirects(false);
        con.setRequestMethod("GET");
        String cookie = con.getHeaderField("Set-Cookie");
        CheckCode checkCode = new CheckCode();
        checkCode.setCookie(cookie);
        ossService.upload(key, con.getInputStream());
        checkCode.setCodeUrl(ossService.getUrl(key).toString());
        return checkCode;
    }

    public int Login_JW(String user, String pwd, String checkcode, String cookie) {
        //返回结果
        //<script language='javascript' defer>alert('密码错误！！');document.getElementById('txtUserName').focus();</script>
        //<script language='javascript' defer>alert('验证码不正确！！');document.getElementById('TextBox2').focus();</script>
        //<script language='javascript' defer>alert('用户名不存在或未按照要求参加教学活动！！');document.getElementById('txtUserName').focus();</script>
        //<html><head><title>Object moved</title></head><body>
        //    <h2>Object moved to <a href='/xs_main.aspx?xh=202160831'>here</a>.</h2>
        //    </body></html>
//        alert('为保障您的个人信息的安全，请点在退出时，请击安全退出！')
        try {
            //获取viewstate
            this.responseCookie = cookie;

            this.xh = user;
            this.mm = pwd;
            this.main_url = "http://jwjx.njit.edu.cn/xs_main.aspx?xh=" + xh;
            Map<String, String> header = new LinkedHashMap<>();
            header.put("contentType", "GB2312");
            header.put("Referer", "http://jwjx.njit.edu.cn/default2.aspx");
            header.put("Cookie", responseCookie);
            Map<String, String> params = new LinkedHashMap<>();
            String get_result = doGet(login_url, null);
            viewState = getViewState(get_result);
            params.put("__VIEWSTATE", viewState);
            params.put("txtUserName", xh);
            params.put("TextBox2", mm);
            params.put("txtSecretCode", checkcode);
            params.put("RadioButtonList1", "学生");
            params.put("Button1", "");
            params.put("lbLanguage", "");
            params.put("hidPdrs", "");
            params.put("hidsc", "");
            String result = doPost("http://jwjx.njit.edu.cn/default2.aspx", header, params);
            String redUrl = con.getHeaderField("Location");
            if (result.contains("<script language='javascript' defer>alert('验证码不正确！！');")) {
                return STATE_LOGIN_JW_CHECKCODE_ERROR;
            }
            if (redUrl != null && redUrl.contains("/zdy.htm?aspxerrorpath")) {
                return STATE_LOGIN_JW_REPAIRED;
            } else if (result.contains("<script language='javascript' defer>alert('用户名不存在或未按照要求参加教学活动！！');")) {
                return STATE_LOGIN_JW_USER_NOT_EXIST;
            } else if (result.contains("<script language='javascript'>alert('密码错误")) {
                return STATE_LOGIN_JW_PASSWORD_ERROR;
            } else if (responseCode == 302) {
                return STATE_LOGIN_JW_SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return STATE_LOGIN_JW_FAILED;
    }


    public void toIndex() {

        //获取用户的名字
        Map<String, String> cookieMap = new HashMap();
        cookieMap.put("Cookie", responseCookie);
        cookieMap.put("Referer", "http://jwjx.njit.edu.cn/default2.aspx");
        String welcomeUrl = "http://jwjx.njit.edu.cn/xs_main.aspx?xh=" + xh;
        currentPage = "http://jwjx.njit.edu.cn/xs_main.aspx?xh=" + xh;
        String info = doGet(welcomeUrl, cookieMap);
        Document document = Jsoup.parse(info);
        Element element = document.getElementById("xhxm");
        this.name = element.text().replaceAll("同学", "");
        VIEWSTATE = document.select("input[name=__VIEWSTATE]").get(0).attr("value");
    }


    /**
     * 如果当前用户存在评教课程，返回list<String[]>，<br>
     * s[0]:课程代码 s[1]:课程名称<br>
     * 如果没有评教，返回null
     *
     * @return
     */
    public ArrayList<String[]> getOnekey_comment_info() {
        ArrayList<String[]> list = new ArrayList<>();
        Map<String, String> header = new LinkedHashMap<>();
        header.put("Cookie", responseCookie);
        header.put("Referer", login_url);
        String result = doGet(main_url, header);
        Document doc = Jsoup.parse(result);
        Elements e = doc.select("li.top");

        int num_need_comment = 0;
        //获取需要评教的课程及代码
        for (Element element : e) {
            //第三栏为评教栏目
            if (element.toString().contains(" 教学质量评价")) {
                Elements ul = element.select("ul.sub");
                Elements li = ul.select("li");
                Elements a = li.select("a");
                for (Element href : a) {
                    num_need_comment++;
                    //评教代码
                    String str_href = href.attr("href");
                    int start = str_href.indexOf("xkkh=") + 5;
                    int end = str_href.indexOf("&", start);
                    String code = str_href.substring(start, end);
                    //评教名称
                    String name = href.text();
                    list.add(new String[]{code, name});
                }
                break;
            }

        }
        if (num_need_comment == 0) {
            return new ArrayList<>();
        } else {
            return list;
        }
    }

    /**
     * @param list getOnekey_comment_info()方法的返回值
     * @return -1：不需评教<br> int型：表示评教成功的数量
     */
    public int onekey_comment(ArrayList<String[]> list) {
        if (list.size() == 0) {
            return 0;
        }
        int comment_success_num = 0;
        if (list == null) {
            return -1;
        } else {
            //获取第一项的__VIEWSTATE
            Map<String, String> init_header = new LinkedHashMap<>();
            init_header.put("Cookie", responseCookie);
            init_header.put("Referer", main_url);
            String str = doGet("http://jwjx.njit.edu.cn/xsjxpj.aspx?xkkh=" + list.get(0)[0] + "&xh=" + xh + "&gnmkdm=N12141", init_header);
            VIEWSTATE = getViewState(str);
            //遍历评教，每次返回结果里包含下一次评教的__VIEWSTATE
            for (int i = 0; i < list.size() + 1; i++) {
                String code = "";
                if (i == list.size()) {
                    code = list.get(i - 1)[0];
                } else {
                    code = list.get(i)[0];
                }
                String post_str = "http://jwjx.njit.edu.cn/xsjxpj.aspx?xkkh=" + code + "&xh=" + xh + "&gnmkdm=N12141";
                Map<String, String> header = new LinkedHashMap<>();
                header.put("Cookie", responseCookie);
                header.put("Referer", "http://jwjx.njit.edu.cn/xsjxpj.aspx?xkkh=" + code + "&xh=" + xh + "&gnmkdm=N12141");
                Map<String, String> params = new LinkedHashMap<>();
                params.put("__EVENTTARGET", "");
                params.put("__EVENTARGUMENT", "");
                params.put("__VIEWSTATE", VIEWSTATE);
                for (int j = 2; j < 13; j++) {
                    if (j == 3) {
                        params.put("DataGrid1:_ctl" + j + ":JS1", "比较满意");
                    } else {
                        params.put("DataGrid1:_ctl" + j + ":JS1", "非常满意");
                    }
                    params.put("DataGrid1:_ctl" + j + ":txtjs1", "");
                }
                params.put("pjkc", code);
                params.put("pjxx", "");
                params.put("txt1", "");
                params.put("TextBox1", "0");
                if (i == list.size()) {
                    params.put("Button2", "提  交");
                } else {
                    params.put("Button1", "保  存");
                }
                String result = doPost(post_str, header, params);

                //保存倒数第二项给最后一项的__VIEWSTATE，用此来提交
                if (i == list.size() - 1) {

                } else {
                    VIEWSTATE = getViewState(result);
                }
                comment_success_num++;
            }
        }
        return comment_success_num;
    }

//    public static void main(String[] args) throws Exception {
//        JWLoginUtil util = new JWLoginUtil();
////        InputStream inputStream = util.getCheckCode();
//
//        File file = new File("./code.png");
//        FileOutputStream fos = new FileOutputStream(file);
//        byte[] bytes = new byte[1024];
//        int len = 0;
//        while((len = inputStream.read(bytes))!=-1){
//            fos.write(bytes, 0, len);
//        }
//
//        fos.flush();
//        fos.close();
//
//        Scanner scanner = new Scanner(System.in);
//        String code = scanner.nextLine();
//        util.Login_JW("202160818", "Hcq199885", code);
//        util.toIndex();
//        ArrayList<String[]> list = util.getOnekey_comment_info();
//
//        util.onekey_comment(list);
//    }


}
